<template>
  <div class="contractTemplate app-container">
    <div class="content">
      <div class="contentBox">
        <div class="search">
          <el-form
            :inline="true"
            :model="searchFrom"
            class="demo-form-inline"
            id="searchFrom"
          >
            <el-form-item style="margin: 0 5px 20px">
              <el-input
                v-model="searchFrom.title"
                placeholder="输入搜索关键词"
                clearable
              />
            </el-form-item>
            <el-form-item style="margin: 0 5px 20px">
              <el-select
                v-model="searchFrom.status"
                placeholder="模板状态"
                clearable
              >
                <el-option
                  v-for="item in templace_status"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                />
                <!-- <el-option label="停用" value="2" /> -->
              </el-select>
            </el-form-item>
            <el-form-item style="margin: 0 5px 20px">
              <el-select
                v-model="searchFrom.type"
                placeholder="模板类型"
                clearable
              >
                <el-option
                  v-for="item in contract_template_type"
                  :key="item.label + item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="margin: 0 5px 20px; width: 240px">
              <el-date-picker
                v-model="searchFrom.createTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                unlink-panels
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                placeholder="发布时间"
                clearable
              />
            </el-form-item>
            <el-form-item style="margin: 0 5px 20px">
              <el-input
                placeholder="发布人员"
                v-model="searchFrom.createName"
                @click="selectCreatePerson"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-tree-select
                v-model="searchFrom.orgId"
                :data="department"
                :props="props"
                :height="208"
                placeholder="归属公司"
                clearable
                :disabled="needDisabled"
              />
            </el-form-item>
            <el-form-item style="margin: 0 5px 20px">
              <el-button type="primary" @click="onSubmit"
                ><el-icon><Search /></el-icon>查询</el-button
              >
              <el-button type="default" @click="reset"
                ><el-icon><RefreshLeft /></el-icon>重置</el-button
              >
            </el-form-item>
          </el-form>
          <div>
            <el-button type="primary" @click="newTemplate"
              ><el-icon><Plus /></el-icon>新建模板</el-button
            >
            <el-button
              type="primary"
              plain
              @click="editEvent"
              :disabled="isDisabled"
            >
              <el-icon><Edit /></el-icon>编辑模板</el-button
            >
            <el-button
              @click="delEvent"
              type="primary"
              plain
              :disabled="isDisabled"
              ><el-icon><DeleteFilled /></el-icon>删除模板</el-button
            >
          </div>
        </div>
        <div class="tableBox">
          <el-table
            :data="dataList"
            border
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="title" label="合同模板标题" />
            <el-table-column prop="status" label="模板状态" align="center">
              <template v-slot="scope">
                <dict-drop
                  :options="templace_status"
                  :value="scope.row.status"
                ></dict-drop>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="模板类型" align="center">
              <!-- <template v-slot="scope">
                <div>
                  {{ constantFilter(contract_template_type, scope.row.type) }}
                </div>
              </template> -->
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="发布时间"
              align="center"
            />
            <el-table-column
              prop="createName"
              label="发布人员"
              align="center"
            />
            <el-table-column prop="viewRange" label="公开状态" align="center">
            </el-table-column>
            <el-table-column prop="orgName" label="归属公司" align="center">
            </el-table-column>
          </el-table>
          <pagination
            :total="searchFrom.total"
            v-model:page="searchFrom.pageNum"
            v-model:limit="searchFrom.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>
    <SelectDialog
      :dialogParam="dialogParam"
      @ok="selectData"
      @close="cancel"
    ></SelectDialog>
  </div>
</template>

<script setup name="ContractTemplate">
import { reactive, getCurrentInstance, toRefs, ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { contractList, contractDelete } from '@/api/salesManage/contractManage'
import SelectDialog from '@/components/SelectDialog/index.vue'
import useCommonStore from '@/store/modules/common'
import {
  contract_template_type,
  templace_status,
  open_state
} from '@/hooks/dict/contract'

import useUserStore from '@/store/modules/user'
const router = useRouter()
const userStore = useUserStore()
console.log(userStore, 'userStore')
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const props = {
  value: 'id',
  label: 'label',
  children: 'children'
}
// 省公司 查看全部 / 分公司 无法筛选
const needDisabled = computed(() => {
  return userStore.userInfo.orgId != '484'
})
const data = reactive({
  searchFrom: {
    title: null, // 名称
    status: null, // 状态
    type: null, // 类型
    createTime: [], // 时间范围
    createName: null, // 发布人员
    createTimeBegin: null,
    createTimeEnd: null,
    pageStyle: [10, 15, 20],
    pageSize: 10,
    total: 0,
    pageNum: 1,
    orgId: userStore.userInfo.orgId
  },
  dataList: [],
  // 选中行数
  rowNum: 0,
  department: [],
  dialogParam: {}
})

const ctId = ref()
const { searchFrom, dataList, page, dialogParam, department } = toRefs(data)

function cancel() {
  dialogParam.value.isDialog = false
}
async function init() {
  getList()
  const res = await commonStore.getUseTreeData()
  department.value = await commonStore.getCompanyData()
  dialogParam.value = {
    type: 'viewPersons',
    nodeKey: 'uuid',
    isDialog: false,
    data: [res[0]],
    multiple: false,
    defaultCheckedKeys: [],
    checkStrictly: false,
    title: '发布人员选择'
  }
}

function getList() {
  contractList(searchFrom.value).then(res => {
    dataList.value = [...res.data.records]
    nextTick(() => {
      dataList.value.forEach(v => {
        v.viewRange = ref(open_state).value[Number(v.viewRange)].label
        v.type = ref(contract_template_type).value[Number(v.type)].label
      })
    })

    searchFrom.value.total = res.data.total
  })
}

const isDisabled = computed(() => {
  return (
    data.rowNum != 1 ||
    selectRow.value[0]?.createBy != userStore.userInfo.userName
  )
})
const selectRow = ref([])
function handleSelectionChange(row) {
  data.rowNum = row.length
  selectRow.value = row
  ctId.value = row.map(item => item.ctId)
}

function newTemplate() {
  router.push({
    path: '/sales/contract/addTemplate',
    query: {}
  })
}
function editEvent() {
  if (!data.rowNum) {
    proxy.$modal.msgWarning('请选择一行数据')
    return
  }
  if (data.rowNum > 1) {
    proxy.$modal.msgWarning('当前功能不可多选行')
    return
  }

  router.push({
    path: '/sales/contract/examineTemplate',
    query: { id: ctId.value }
  })
}
function delEvent() {
  if (!data.rowNum) {
    proxy.$modal.msgWarning('请选择一行数据')
    return
  }
  proxy.$modal
    .confirm('是否确认删除?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      contractDelete(ctId.value)
        .then(res => {
          proxy.$modal.msgSuccess('删除成功')
          getList()
        })
        .catch(err => {
          console.log(err)
          // proxy.$modal.msgError('删除失败')
        })
    })
}
// 查询类别
const onSubmit = function (e) {
  e.preventDefault()
  if (searchFrom.value.createTime && searchFrom.value.createTime.length) {
    searchFrom.value.createTimeBegin =
      searchFrom.value.createTime[0] + ' 00:00:00'
    searchFrom.value.createTimeEnd =
      searchFrom.value.createTime[1] + ' 23:59:59'
  } else {
    searchFrom.value.createTimeBegin = null
    searchFrom.value.createTimeEnd = null
  }
  getList()
}

const reset = function () {
  searchFrom.value = {
    title: null, // 名称
    status: null, // 状态
    type: null, // 类型
    createTime: [], // 时间范围
    createName: null, // 发布人员
    createTimeBegin: null,
    createTimeEnd: null,
    pageNum: 1,
    pageSize: 10,
    orgId: userStore.userInfo.orgId
  }
  getList()
}

function handleCurrentChange(val) {
  // ('页码改变', val)
  searchFrom.value.pageNum = val
  getList()
}
function handleSizeChange(val) {
  // ('显示条数改变', val)
  searchFrom.value.pageSize = val
  getList()
}

function constantFilter(dict, id) {
  if (dict && id) {
    const ietm = dict.value.filter(item => {
      if (item.value === id) {
        return item
      }
    })[0]
    console.log(ietm, 'item')
    return ietm.label ? ietm.label : ''
  }
}

function selectCreatePerson() {
  dialogParam.value.isDialog = true
}
function selectData(val) {
  searchFrom.value.createName = val.labelData[0]
  dialogParam.value.isDialog = false
  dialogParam.value.defaultCheckedKeys = val.defaultCheckedKeys
}

init()
</script>
<style lang="scss" scoped>
.contractTemplate {
  .content {
    .contentBox {
      .search {
        @apply pb-30px;
      }
      .tableBox {
        .statusTip {
          @apply inline-block mr-5px;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: rgb(25, 190, 107);
        }
        .red-bg {
          background-color: red;
        }
        .yellow-bg {
          background-color: rgb(245, 166, 144);
        }
        .footer {
          width: 100%;
          @apply flex flex-row-reverse my-4;
        }
      }
    }
  }
}
</style>
